<?php
include_once __DIR__ . '/../config.php';
use PhpAmqpLib\Connection\AMQPStreamConnection;
use PhpAmqpLib\Message\AMQPMessage;

class FibonacciRpcClient {
    private $connection;
    private $channel;
    private $callback_queue;
    private $response;
    private $corr_id;

    public function __construct() {
        $this->connection = new AMQPStreamConnection(HOST,PORT,USER,PASS,VHOST);
        $this->channel = $this->connection->channel();

        list($this->callback_queue, ,) = $this->channel->queue_declare("", false, false, true, false);

        $this->channel->basic_consume(
            $this->callback_queue, '', false, false, false, false,
            array($this, 'on_response')
        );
    }

    public function on_response($rep) {
        if($rep->get('correlation_id') == $this->corr_id) {
            $this->response = $rep->body;
        }
    }

    public function call($n) {
        $this->response = null;
        $this->corr_id = uniqid();

        $msg = new AMQPMessage(
            (string) $n,
            array('correlation_id' => $this->corr_id,'reply_to' => $this->callback_queue)
        );

        $this->channel->basic_publish($msg, '', 'rpc_queue');

        var_dump($this->response);

        while(!$this->response) {

            var_dump($this->response);

            sleep(1);

            var_dump(3);

            $this->channel->wait();

            var_dump(59877);
            var_dump($this->response);
        }

        var_dump(4444);
        return intval($this->response);
    }
};

//创建一个rpc客户端类，并且暴露 call 方法用来调用rpc请求，在收到server服务响应之前进行阻塞
$fibonacci_rpc = new FibonacciRpcClient();

$response = $fibonacci_rpc->call(30);

echo " [.] Got ", $response, "\n";

?>